package com.example.news;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.example.news.apapter.NewsAdapter;
import com.example.news.dao.HistoryDao;
import com.example.news.databinding.NewsListItemBinding;
import com.example.news.entity.History;
import com.example.news.entity.News;
import com.example.news.entity.Userinfo;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author Admin
 */
public class HistoryListActivity extends AppCompatActivity {
    public static final String TAG = "HistoryListActivity-LOG";
    private Toolbar toolbar;
    private NewsAdapter newsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_list);

        toolbar = findViewById(R.id.toolbar);

        findViewById(R.id.toolbar).setOnClickListener(v -> finish());

        RecyclerView recycleView = findViewById(R.id.recycleView);

//        List<History> histories = History.listAll(History.class);
//        Log.d(TAG, "onCreate: histories " + histories.size());

        newsAdapter = new NewsAdapter(this);
        List<News.ResultDTO.DataDTO> list = data();
        newsAdapter.setList(list);

        recycleView.setAdapter(newsAdapter);
        // 设置点击事件
        newsAdapter.setOnItemClickListener(new NewsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(News.ResultDTO.DataDTO dataDTO, int position) {
                Intent intent = new Intent(HistoryListActivity.this, NewsDetailsActivity.class);
                // 把整个对像传过去
                // 要传递的对象必须要实现 Serializable
                intent.putExtra(TabNewsFragment.DATA_DTO, dataDTO);
                startActivity(intent);
            }
        });
    }
    private List<News.ResultDTO.DataDTO> data(){
        List<News.ResultDTO.DataDTO> list = new ArrayList<>();
        Userinfo userinfo = Userinfo.getUserinfo();
        if (Objects.nonNull(userinfo)) {
            List<History> histories = HistoryDao.queryHistory(userinfo.getUserName());
            for (History history : histories) {
                String context = history.getContext();
                News.ResultDTO.DataDTO dataDTO = new Gson().fromJson(context, News.ResultDTO.DataDTO.class);
                list.add(dataDTO);
            }
        }
        return list;
    }
}